/*
 * @Author: 专送Pro
 * @Date: 2019-08-08 10:05:31
 * @LastEditors  : wuzhen
 * @LastEditTime : 2020-01-11 10:50:26
 * @Description: 路由配置
 */
import Vue from "vue";
import Router from "vue-router";
import iView from "iview";
import config from "@/config";
import store from "@/store";

// 概况
import monitorManagement from "./monitorManagement";
// 用户管理
import userManagement from "./userManagement";
// 群组管理
import groupManagement from "./groupManagement";
// 系统公告
import noticeManagement from "./noticeManagement";
// 举报管理
import reportManagement from "./reportManagement";
// 单聊记录
import singleChatRecord from "./singleChatRecord";
// 系统管理
import system from "./system";

Vue.use(Router);

export const asyncRoutes = [
  ...monitorManagement,
  ...userManagement,
  ...groupManagement,
  ...noticeManagement,
  ...reportManagement,
  ...singleChatRecord,
  ...system
];

const router = new Router({
  mode: config.routerMode, // hash
  base: process.env.BASE_URL,
  routes: [
    ...[
      {
        path: "/login",
        name: "login",
        meta: {
          title: "Login - 登录",
          hideInMenu: true
        },
        component: () => import("@/views/login")
      },
      {
        path: "/",
        component: () => import("@/views/dashboard"),
        redirect: { name: config.homeName },
        children: asyncRoutes,
        meta: {
          title: "首页"
        }
      },
      {
        path: "/401",
        name: "errorPage401",
        component: () => import("@/views/errorPage/401")
      },
      {
        path: "/404",
        name: "errorPage404",
        component: () => import("@/views/errorPage/404")
      }
    ]
    // ...asyncRoutes
  ]
});

// 白名单免登陆
const whiteList = [
  "login",
  "userManagement-friends",
  "groupManagement-users",
  "groupManagement-chatRecord"
];

router.beforeEach((to, from, next) => {
  const routerMenus = store.state.user && store.state.user.routerMenus;
  const currentMenu = routerMenus.find(v => v.webRouterKey === to.name);
  if (currentMenu) {
    to.meta["title"] = currentMenu["text"];
  }
  // 开启进度条
  iView.LoadingBar.start();
  next();
  if (whiteList.indexOf(to.name) !== -1) {
    // 在免登录白名单，直接进入
    next();
  } else if (store.state.user.token) {
    // 根据token判断用户是否处于登录状态
    if (to.path === "/login") {
      next({
        path: "/",
        replace: true
      });
    } else if (to.path.indexOf("/404") >= 0 || to.path.indexOf("/401") >= 0) {
      // 防止因重定向到error页面造成beforeEach死循环
      next();
    } else if (to.matched.length === 0) {
      next("/401");
      store.dispatch("LogOut");
    } else if (!currentMenu) {
      // 未匹配到路由
      next("/404");
      store.dispatch("LogOut");
    } else {
      next();
    }
  } else {
    iView.Message.info("您还未登录，请先登录");
    next(`/login?redirect=${to.path}`); // 否则全部重定向到登录页
  }
});

router.afterEach(() => {
  iView.LoadingBar.finish();
});

export default router;
